package com.eastfair.gateway.service.impl;

import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.certificate.CertificateOrderCacheKeyBuilder;
import com.eastfair.cache.gateway.BlockListCacheKeyBuilder;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.utils.SpringUtils;
import com.eastfair.gateway.dao.BackListMapper;
import com.eastfair.gateway.entity.BackList;
import com.eastfair.gateway.service.BackListService;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.point.business.gateway.BusinBalckPoint;
import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.core.base.R;

import java.time.LocalDateTime;
import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import com.eastfair.gateway.vo.*;
import com.eastfair.gateway.dto.*;

/**
 * <p>
 * 业务实现类
 * 黑名单
 * </p>
 *
 * @author ligang
 * @date 2022-07-30
 */
@Slf4j
@Service
////@DS("#thread.tenant")
public class BackListServiceImpl extends SuperCacheServiceImpl<BackListMapper, BackList> implements BackListService {

    @Autowired
    BackListService backListService;

    @Autowired
    SnowFlakeRole snowFlakeRole;
    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(BackList model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setTenantId(ContextUtil.getProjectId());
        //雪花ID
        model.setId(snowFlakeRole.findUidSimple());
        return R.successDef();
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<BackList> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(1);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<BackList> list(BackListDTO modelDTO, List<Long> ids) {
        return listOfCache(modelDTO,ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'ip', #args[0]?.ip}," +
                            "{'userId', #args[0]?.userId}," +
                            "{'userId', #args[0]?.userId}," +
                            "{'idCard', #args[0]?.idCard}," +
                            "{'mobile', #args[0]?.mobile}," +
                            "{'email', #args[0]?.email}," +
                            "{'limitStart', #args[0]?.limitStart}," +
                            "{'limitEnd', #args[0]?.limitEnd}," +
                            "{'systemScene', #args[0]?.systemScene}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<BackList> listOfCache(BackListDTO modelDTO, List<Long> ids) {
        //查询
        QueryWrapper<BackList> queryWrapper = new QueryWrapper<>();
        if (modelDTO != null) {
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getIp()), BackList::getIp, modelDTO.getIp());
            queryWrapper.lambda().eq(modelDTO.getUserId()!=null, BackList::getUserId, modelDTO.getUserId());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getIdCard()), BackList::getIdCard, modelDTO.getIdCard());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getMobile()), BackList::getMobile, modelDTO.getMobile());
            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getEmail()), BackList::getEmail, modelDTO.getEmail());
            queryWrapper.lambda().ge(StringUtils.isNotBlank(modelDTO.getLimitStart()), BackList::getLimitStart, modelDTO.getLimitStart());
            queryWrapper.lambda().le(StringUtils.isNotBlank(modelDTO.getLimitEnd()), BackList::getLimitEnd, modelDTO.getLimitEnd());
            queryWrapper.lambda().eq(modelDTO.getSystemScene() != null, BackList::getSystemScene, modelDTO.getSystemScene());
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(BackList::getId, ids);
        }
        queryWrapper.lambda().eq(BackList::getIsDeleted, 0);
        List<BackList> modelList = list(queryWrapper);
        return modelList;
    }

    @Override
    public BackList executeAddBackList(BackListDTO backListDTO, LocalDateTime startTime,LocalDateTime endTime) {
        List<BackList> backListList = list(backListDTO,null);
        BackList backList = new BackList();
        if(backListList!=null && !backListList.isEmpty()){
            backList = backListList.get(0);
            backList.setLimitStart(startTime);
            backList.setLimitEnd(endTime);
            backList.setIsEnabled(BusinessConstant.YES);
            updateById(backList);
        }else {
            BeanUtils.copyProperties(backListDTO,backList);
            backList.setLimitStart(startTime);
            backList.setLimitEnd(endTime);
            backList.setIsEnabled(BusinessConstant.YES);
            save(backList);
        }
        return backList;
    }


    @Override
    public List<BackList> queryBackList(BackListDTO backListDTO) {
        return listOfCache(backListDTO,null);
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public BackListVO doToVo(BackList model) {
        BackListVO modelVo = new BackListVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<BackListVO> doToVos(List<BackList> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<BackListVO> result = new ArrayList<>();
        for (BackList model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new BlockListCacheKeyBuilder();
    }
}
